<template>
    <!-- 质量整改通知单业务待办 -->
    <!-- <base-breadcrumb :title="$route.meta.title"> -->
    <div>
      <a-spin :spinning="loading">
        <!-- 问题信息 -->
        <a-card :bordered="false">
          <title-name title="处理"></title-name>
          <div class="ml12">
            <title-name title="复核风险信息"></title-name>
            <custom-form ref="ruleForm" isValidate :formList="formList" :form="form" :editModel="'E'"
              :isEmit="false">
                <!-- 调整风险损失 -->
                <template slot="riskTableLast" slot-scope="scoped">
                  <a-table
                      style="margin-top: 20px;"
                      :pagination="false"
                      size="default"
                      :rowKey="(record, index) => record ? (record.id + index) : index"
                      bordered
                      :columns="columnsReview"
                      :data-source="dataSourceReview"
                    ></a-table>
                </template>
                <template slot="isQualityRisk" slot-scope="text, record">
                  <a-switch v-model="form.isQualityRisk" checked-children="是" un-checked-children="否" :disabled="resolveInfo" />
                </template>
                <!-- 调整风险损失 -->
                <template slot="riskTable" slot-scope="scoped">
                  <!-- 新增按钮 -->
                  <a-button size="default" type="primary" @click="visible = true" v-if="!resolveInfo"> 选择 </a-button>
                  <a-table
                    style="margin-top: 20px;"
                    :pagination="false"
                    size="default"
                    :rowKey="(record, index) => record ? (record.id + index) : index"
                    bordered
                    :columns="resolveInfo ? columnsResolveInfo: columnsBase"
                    :data-source="dataSource"
                  >
                    <!-- 补充描述 -->
                    <template slot="supplementDescription" slot-scope="text, record, index">
                      <EditableCell type="textarea" :auto-size="{ minRows: 1, maxRows: 4 }" :maxLength="300" :key="index + '-supplementDescription'" :text="text" @change="onCellChange(record, 'supplementDescription', $event)" :disabled="record.operation === false"></EditableCell>
                    </template>
                    <!-- 操作 -->
                    <template
                      slot="action"
                      slot-scope="text, record, index"
                    >
                      <a-popconfirm title="请确认是否要删除？" @confirm="() => onDelete(record)">
                        <a class="base-btn del_btn">删除</a>
                      </a-popconfirm>
                    </template>
                  </a-table>
                </template>
            </custom-form>
            <!-- 操作栏 -->
            <div class="btn_box" align="right" v-if="!resolveInfo">
              <a-button type="primary" :loading="auditLoading[0]" @click="handleSubmit(0)">驳回</a-button>
              <a-button type="primary" :loading="auditLoading[1]" class="ml12" @click="handleSubmit(1)">确认处理</a-button>
            </div>
          </div>
        </a-card>
        <!-- 业务详情 -->
        <a-card :bordered="false">
          <h1>业务详情</h1>
          <!-- 基本信息 -->
          <BaseInfo ref="BaseInfo" :form="detailForm" :onlyRead="true" :orgTreeDisabled="false" />
          <!-- 风险上报信息 -->
          <RiskReportingInfo ref="RiskReportingInfo" :form="detailForm" :onlyRead="true" />
        </a-card>
      </a-spin>
      <div class="btn_box tool-btns--fixed page-btn-right-top">
        <a-button type="primary" @click="$close">关闭</a-button>
      </div>
      <a-modal
        centered
        title="风险损失"
        :visible="visible"
        ok-text="选中提交"
        width="1200px"
        @cancel="visible = false"
        @ok="handleConfirm"
      >
        <RiskJudgmentCriteria :isModal="true" ref="RiskJudgmentCriteria" :outSelectedRowKeys="outSelectedRowKeys"></RiskJudgmentCriteria>
      </a-modal>
      </div>
    <!-- </base-breadcrumb> -->
  </template>
  
  <script>
    import EditableCell from '@/views/quality/riskIdentification/components/EditableCell'
  import RiskJudgmentCriteria from '@/views/quality/riskJudgmentCriteria' // 项目
  import BaseInfo from '@/views/quality/riskIdentification/components/BaseInfo'
  import RiskReportingInfo from '@/views/quality/riskIdentification/components/RiskReportingInfo'
  import { riskReporting } from '@/api/quality/risk/riskReporting'
  import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
  const columnsBase = [
    {
      title: '损失类型',
      dataIndex: 'treeName',
      width: 180,
    },
    {
      title: '损失描述',
      ellipsis: true,
      dataIndex: 'description',
    },
    {
      title: '补充描述',
      dataIndex: 'supplementDescription',
      scopedSlots: { customRender: 'supplementDescription' },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      scopedSlots: { customRender: 'action' },
    }
  ]
  const columnsResolveInfo = [
    {
      title: '损失类型',
      dataIndex: 'treeName',
      width: 180,
    },
    {
      title: '损失描述',
      ellipsis: true,
      dataIndex: 'description',
    },
    {
      title: '补充描述',
      ellipsis: true,
      dataIndex: 'supplementDescription'
    },
  ]
  const columnsReview = [
    {
      title: '损失类型',
      dataIndex: 'treeName',
      width: 180,
    },
    {
      title: '损失描述',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '补充描述',
      ellipsis: true,
      dataIndex: 'supplementDescription',
    },
  ]
  export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    components: {
      RiskJudgmentCriteria,
      BaseInfo,
      RiskReportingInfo,
      EditableCell,
    },
    data() {
      return {
        bussinessId: this.$route.query.bussinessId || '',
        escalationId: this.$route.query.escalationId || '',
        auditLoading: {0: false, 1: false},
        loading: false, // 请求加载框
        detailForm: {
          projectId:"",
          updateUserName: this.$userInfo().name,
          fillTime: this.$dateFormat(Date.now(), 'D'),
        },
        form: {
          isQualityRisk: true,
          proposal: '',
        },
        api: riskReporting, // 请求api
        visible: false,
        dataSource: [],
        dataSourceReview: [],
        outSelectedRowKeys: [],
        columnsBase,
        columnsResolveInfo,
        columnsReview,
      }
    },
    created() {
      // 请求业务详情
      this.init()
      document.title = '中建八局'
    },
    computed: {
    // 是否是业务待办查看处理信息
    resolveInfo: {
      get() {
        return this.$route.query?.resolveInfo === 'true'
      },
      set() {}
    },
      // 表单配置项
      formList() {
        let list = []
        if (this.dataSourceReview.length > 0) {
          list.push(
            {
              slot: true,
              keyName: 'riskTableLast',
              label: '风险损失',
              disabled: true,
              span: 24
            }
          )
        }
        list.push(
          {
            slot: true,
            keyName: 'isQualityRisk',
            label: '是否为质量风险',
          },
        )
        if (this.form.isQualityRisk) {
         const isQualityRiskList = [
            {
              slot: true,
              keyName: 'riskTable',
              label: '调整风险损失',
              disabled: true,
              span: 24
            },
            {
              type: 'a-input',
              keyName: 'levelName',
              label: '上报风险等级',
              disabled: true,
            },
          ]
          list = list.concat(isQualityRiskList)
        }
        list.push({
            type: 'BaseTextarea',
            keyName: 'proposal',
            label: '补充处理意见',
            disabled: this.resolveInfo,
            attrs: {
              maxLength: 1000
            },
            rule: {
              required: true,
              whitespace: true,
              message: '请输入补充处理意见',
              trigger: 'change'
            },
            span: 24
          },
        )
        return list
      },
    },
    methods: {
      /**
       * @description: 请求业务详情
       */
      init() {
        if (this.escalationId) {
          this.loading = true
          this.api
            .getDetail(this.escalationId, this.bussinessId)
            .then((res) => {
              if (res.data) {
                const data = res.data
                // 映射表单
                res.data.projectTypeId = res.data.projectTypeId ? res.data.projectTypeId.toString(): ''
                res.data.subProjectId = res.data.subProjectId ? res.data.subProjectId.toString(): ''
                this.detailForm = res.data
                this.detailForm.viewName = res.data.branchComName + '/' + res.data.projectName
                if (data.last && data.last.lossInfos) {
                  this.dataSourceReview = data.last.lossInfos.map(item => {
                      if (item.type) {
                        item.level = item.level || item.type.level
                        item.description = item.description || item.type.description
                        item.treeName = item.treeName || item.type.treeName
                      }
                      return item
                  })
                } else {
                  this.dataSourceReview = []
                }
                if (this.resolveInfo) {
                  if (data.next) {
                    if (data.next.lossInfos) {
                      this.dataSource = data.next.lossInfos.map(item => {
                          if (item.type) {
                            item.level = item.level || item.type.level
                            item.description = item.description || item.type.description
                            item.treeName = item.treeName || item.type.treeName
                          }
                          return item
                      })
                    } else {
                      this.dataSource = []
                    }
                    this.form.proposal = data.next.proposal
                    this.form.levelName = data.next.level.name
                  } else {
                    this.dataSource = []
                    this.form.proposal = ''
                    this.form.levelName = ''
                  }
                }
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      },
      handleConfirm() {
        if (this.$refs.RiskJudgmentCriteria.selectRow) {
          const selectRow = this.$refs.RiskJudgmentCriteria.selectRow
          const arr = this.dataSource.concat(selectRow)
          const obj = {}
          this.dataSource = arr.reduce((total, currentValue) => {
            obj[currentValue.id] ? '' : (obj[currentValue.id] = true && total.push(currentValue))
            return total
          }, [])
          this.dataSource = this.dataSource.map(item => {
            if (!item.hasOwnProperty('supplementDescription')) {
              item.supplementDescription = ''
            }
            return item
          })
          this.outSelectedRowKeys = selectRow.map(item => item.id)
          this.handleData()
          this.visible = false
        }
      },
      handleData() {
        const levelCode = []
        const levelName = ['一般风险', '较大风险', '重大风险', '特大风险']
        this.dataSource.forEach(item => {
          if (item.level && item.level.code) {
            if (!levelCode.includes(item.level.code)) {
              levelCode.push(+item.level.code)
            }
          }
        });
        this.form.levelName = levelName[Math.max(...levelCode)]
      },
      onDelete(item) {
        const dataSource = [...this.dataSource]
        this.dataSource = dataSource.filter((el) => el.id !== item.id)
        this.outSelectedRowKeys = this.dataSource.map(item => item.id)
        this.handleData()
      },
      onCellChange(item, dataIndex, value) {
        const dataSource = [...this.dataSource]
        const target = dataSource.find((el) => el.id === item.id)
        if (target) {
          target[dataIndex] = value
          this.dataSource = dataSource
        }
      },
      /**
       * @description: 处理
       * @return {*}
       */
      handleSubmit(type) {
        this.$refs?.ruleForm.validate(valid2=> {
          if (valid2) {
            if (this.form.isQualityRisk) {
              // const columns = this.columns || []
              const dataSource = this.dataSource || []
              if (dataSource.length === 0) {
                this.$warning({
                  title: '提示',
                  content: '调整风险损失不能为空！',
                  okText: '确定'
                })
                return false
              }
              // const emtyArr = dataSource.filter((obj) => {
              //   let tag = false
              //   for (let key in obj) {
              //     if (columns.indexOf(key) !== -1 && !obj[key]) {
              //       tag = true
              //       break;
              //     }
              //   }
              //   return tag;
              // })
              // if (emtyArr.length) {
              //   this.$warning({
              //     title: '提示',
              //     content: '请将调整风险损失填写完整再提交！',
              //     okText: '确定'
              //   })
              //   return false
              // }
            }
            const submitName = ['驳回', '提交'][type]
            this.$confirm({
              titile: '提示',
              content: `确认${submitName}，${submitName}后不可撤回？`,
              onOk: () => {
                const submitData = {
                  status: type ? '2' : '3',
                  bussinessId: this.bussinessId,
                  escalationId: this.escalationId,
                  isQualityRisk: this.form.isQualityRisk,
                  proposal: this.form.proposal,
                }
                if (this.form.isQualityRisk) {
                  const dataSource = this.dataSource || []
                  submitData.losses = dataSource.map(item => {
                    const json = {
                      typeId: item.id,
                      supplementDescription: item.supplementDescription || '',
                    }
                    return json
                  })
                }
                this.auditLoading[type] = true
                this.api.audit(submitData).then(res => {
                  if (res.code === 200 || res.data.code === 200) {
                    this.$message.success(submitName + '成功！')
                    this.$multiTab.close()
                  }
                }).finally(() => {
                  this.auditLoading[type] = false
                })
              }
            })
          }
        })
      },
    }
  }
  </script>